<!--
- File:    编辑成长日志.
-->
<template>
  <div class="Web_Box">
    <div class="bg_fff">
      <!--<div class="add_time f-cb"><span class="fl">日期</span>-->
      <!--<span class="fr" @click="openRentDatePicker"><span class="vm">{{date}}</span><i class="iconfont icon-more"></i></span></div>-->
      <div class="add_statu">
        <h3>成长状态</h3>
        <ul class="f-cb statu_block2">
          <li :class="{'cur': selectedStatus == $dictionary.growthStatus.seed}" @click="switchStatus($dictionary.growthStatus.seed)">
            <i class="iconfont icon-tab_potato_heighlight"></i>
            <p>种子期</p>
          </li>
          <li :class="{'cur': selectedStatus == $dictionary.growthStatus.sprout}" @click="switchStatus($dictionary.growthStatus.sprout)">
            <i class="iconfont icon-zhongzi"></i>
            <p>发芽期</p>
          </li>
          <li :class="{'cur': selectedStatus == $dictionary.growthStatus.seedling}" @click="switchStatus($dictionary.growthStatus.seedling)">
            <i class="iconfont icon-shuye1"></i>
            <p>小苗期</p>
          </li>
          <li :class="{'cur': selectedStatus == $dictionary.growthStatus.growthed}" @click="switchStatus($dictionary.growthStatus.growthed)">
            <i class="iconfont icon-shu1"></i>
            <p>成株期</p>
          </li>
        </ul>
      </div>
      <div class="add_statu">
        <h3>健康状态</h3>
        <div class="graden_cont5" style="padding: 0">
          <ul class="f-cb">
            <li v-for="health in plantAttr.health" @click="switchHealth(health)">
              <div class="graden_bg5" style="width: 40px; height: 40px"><img :src="$config.imgsite + $config.uploadImgSrc + health.d_image + '_w150'">
                <i class="iconfont icon-xuanze" style="line-height: 40px; font-size: 38px;" v-show="health.selected"></i>
              </div>
              <h3>{{health.d_name}}</h3>
            </li>
          </ul>
        </div>
      </div>
      <div class="add_statu">
        <h3>点亮行为</h3>
        <ul class="f-cb statu_block2">
          <li :class="{'cur': actionIsSelected($dictionary.growthAction.watering)}" @click="switchSelectAction($dictionary.growthAction.watering)">
            <i class="iconfont icon-shuidi1"></i>
            <p>浇水</p>
          </li>
          <li :class="{'cur': actionIsSelected($dictionary.growthAction.fertilize)}" @click="switchSelectAction($dictionary.growthAction.fertilize)">
            <i class="iconfont icon-red2"></i>
            <p>施肥</p>
          </li>
          <li :class="{'cur': actionIsSelected($dictionary.growthAction.basin)}" @click="switchSelectAction($dictionary.growthAction.basin)">
            <i class="iconfont icon-flowerpot"></i>
            <p>换盆</p>
          </li>
          <li :class="{'cur': actionIsSelected($dictionary.growthAction.cut)}" @click="switchSelectAction($dictionary.growthAction.cut)">
            <i class="iconfont icon-jiandao"></i>
            <p>修剪</p>
          </li>
          <li :class="{'cur': actionIsSelected($dictionary.growthAction.grubs)}" @click="switchSelectAction($dictionary.growthAction.grubs)">
            <i class="iconfont icon-pachong-"></i>
            <p>病虫害</p>
          </li>
          <li :class="{'cur': actionIsSelected($dictionary.growthAction.sunshine)}" @click="switchSelectAction($dictionary.growthAction.sunshine)">
            <i class="iconfont icon-yangguang"></i>
            <p>光照</p>
          </li>
          <li :class="{'cur': actionIsSelected($dictionary.growthAction.other)}" @click="switchSelectAction($dictionary.growthAction.other)">
            <i class="iconfont icon-yezi"></i>
            <p>其他</p>
          </li>
        </ul>
      </div>
      <div class="edittext">
        <textarea placeholder="添加文字" v-model="note"></textarea>
        <div class="fll_price2 f-cb">
          <div class="fllimg">
            <div id="select-pic">
              <input type="file" id="fileInput1" accept="image/jpeg,image/jpg,image/png,image/gif" style="display: none" @change="fileSelected">
            </div>
            <i class="iconfont icon-tianjia1" @click="getImg" style="pointer-events: auto"></i>
          </div>
          <div class="fllimg" v-for="(img, imgIndex) in imgList" @click="delImg(imgIndex)">
            <img :src="$config.imgsite + $config.uploadImgSrc + img + '_w200'"></div>
        </div>
      </div>
    </div>
    <div class="buttonfinish" @click="updateGrowthNote"><a>提交</a></div>
    <mt-actionsheet
      :actions="actions"
      v-model="sheetVisible">
    </mt-actionsheet>
    <mt-datetime-picker
      ref="rentDatePicker"
      v-model="currentDate"
      type="date"
      year-format="{value} 年"
      month-format="{value} 月"
      date-format="{value} 日"
      @confirm="handleRentDateChange">
    </mt-datetime-picker>
  </div>
</template>

<script>
  import {Actionsheet, DatetimePicker} from 'mint-ui'
  import {mapModules, mapRules} from 'vuet'
  import * as request from '../../../../request'

  export default{
    beforeRouteEnter (to, from, next) {
      request.getPlantAttr().then(data => {
        next(vm => {
          vm.plantAttr = data
        })
      }).catch(e => {
        next()
      })
    },
    mixins: [
      mapModules({growthNoteTmp: 'growthNoteTmp'}),
      mapRules({life: ['growthNoteTmp']})
    ],
    data() {
      return {
        plantId: this.$route.params.id,
        plantAttr: {basin: [], dirt: [], environment: [], health: []},
        date: '选择日期',
        selectedHealthId: '', // 选中的健康状态id
        selectedStatus: '', // 0 种子期 1 小苗期 2 成株期 3 花期 4结果期 9准备期
        selectedActionList: [], // 1浇水 2施肥 3光照 4修剪 5换盆 6日照 7其他
        note: '',
        imgList: [],
        sheetVisible: false,
        actions: [{
          name: '拍照',
          method: this.getFromCamera
        }, {
          name: '从相册选取',
          method: this.getFromAlbum
        }],
        currentDate: new Date()
      }
    },
    components: {
      'mt-actionsheet': Actionsheet,
      'mtDatetimePicker': DatetimePicker
    },
    beforeRouteLeave  (to, from, next) {
      this.$indicator.close()
      next()
    },
    created() {
      // this.$native.weixinShare(window.location.href)
      this.initData()
    },
    mounted() {
      this.$native.weixinShare(window.location.href, '遇花园', null, '')
    },
    methods: {
      initData() {
        this.selectedStatus = this.growthNoteTmp.growth_status
        this.selectedActionList = this.growthNoteTmp.behavior
        this.note = this.growthNoteTmp.content
        this.imgList = this.growthNoteTmp.pictures || []
        this.selectedHealthId = this.growthNoteTmp.h_id
        setTimeout(() => {
          for (let i = 0; i < this.plantAttr.health.length; i++) {
            if (this.plantAttr.health[i].d_id == this.selectedHealthId) {
              this.$set(this.plantAttr.health[i], 'selected', true)
              break
            }
          }
        }, 100)
      },
      switchHealth(health) {
        this.selectedHealthId = health.d_id
        if (health.selected) {
          health.selected = false
          this.selectedHealthId = ''
        } else {
          this.$set(health, 'selected', true)
        }
        for (let i = 0; i < this.plantAttr.health.length; i++) {
          if (this.plantAttr.health[i].d_id == health.d_id) {
            continue
          }
          if (this.plantAttr.health[i].selected) {
            this.plantAttr.health[i].selected = false
          }
        }
      },
      switchStatus(value) {
        this.selectedStatus = value
      },
      switchSelectAction(action) {
        let index = this.selectedActionList.indexOf(action)
        if (index == -1) {
          this.selectedActionList.push(action)
        } else {
          this.selectedActionList.splice(index, 1)
        }
      },
      actionIsSelected(action) {
        if (this.selectedActionList.indexOf(action) != -1) {
          return true
        } else {
          return false
        }
      },
//      getGrowthNoteInfo() {
//        this.$request.getGrowthNoteInfo().then(data => {
//          this.growthNoteInfo = data
//        })
//      },
      updateGrowthNote() {
        if (this.selectedStatus == '') {
          this.$toast('请选择成长状态')
          return
        }
        if (this.selectedHealthId == '') {
          this.$toast('请选择健康状态')
          return
        }
        if (this.selectedActionList.length <= 0) {
          this.$toast('请选择点亮行为')
          return
        }
        let param = {
          g_id: this.growthNoteTmp.g_id,
          h_id: this.selectedHealthId,
          behavior: this.selectedActionList.join(','),
          content: this.note,
          growth_status: this.selectedStatus,
          pictures: this.imgList.join(',')
        }
        this.$request.updateGrowthNote(param).then(data => {
          this.$toast('修改成功')
          this.$router.go(-1)
        })
      },
      openRentDatePicker() {
        this.$refs.rentDatePicker.open()
      },
      handleRentDateChange(value) {
        let date = new Date(value)
        let dateStr = this.$utils.formatDate(date, 'yyyy-MM-dd')
        this.date = dateStr
        console.log(dateStr)
      },
      delImg(index) {
        this.$messageBox.confirm('确定删除图片?').then(action => {
          this.imgList.splice(index, 1)
        }).catch(() => {
        })
      },
      getImg() {
        if (this.imgList.length >= 6) {
          this.$toast('只能选择6张图片~')
          return
        }
        let deviceType = this.$utils.getDeviceType()
        if (deviceType == 'wx-iPhone' || deviceType == 'wx-Android') {
          let wxImgPromiseList = []
          wx.chooseImage({ // eslint-disable-line
            count: 6 - this.imgList.length, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
              for (let i = 0; i < res.localIds.length; i++) {
                var localId = res.localIds[i]
                let promise = this.$utils.wxGetLocalImgData(localId)
                wxImgPromiseList.push(promise)
              }
              Promise.all(wxImgPromiseList).then((imgList) => {
                this.$indicator.open('上传图片中...')
                this.$request.uploadImg(imgList).then(data => {
                  this.imgList = [...this.imgList, ...data]
                }).catch(e => {
                  this.$toast('上传图片失败:' + e.msg)
                }).finally(() => {
                  this.$indicator.close()
                })
              })
            }
          })
        } else if (deviceType == 'iPhone') {
          this.getFromAlbum() // 因为iphone不带capture属性的input 点击后本身就会弹出选择图库或拍照
        } else {
          this.sheetVisible = true
        }
      },
      getFromCamera() {
        var imgInputFile = document.getElementById('fileInput1')
        if (!imgInputFile.hasAttribute('capture')) {
          imgInputFile.setAttribute('capture', 'camera')
        }
        this.$utils.clickFileInput(imgInputFile)
      },
      getFromAlbum() {
        var imgInputFile = document.getElementById('fileInput1')
        if (imgInputFile.hasAttribute('capture')) {
          imgInputFile.removeAttribute('capture')
        }
        this.$utils.clickFileInput(imgInputFile)
      },
      clearInputFile() {
        var self = this
        var selectPic = document.getElementById('select-pic')
        var randomStr = Math.random().toString(36)
        selectPic.innerHTML = '<input id="fileInput1" type="file" title="" ' + randomStr + '"  accept="image/jpeg,image/jpg,image/png,image/gif"  id="fileInput1" style="visibility: hidden" >'
        document.getElementById('fileInput1').addEventListener('change', self.fileSelected)
      },
      fileSelected(e) {
        try {
          var reader = new window.FileReader()
          reader.onload = (e) => {
            if (e.total > 1024 * 1024 * 5) {
              this.$toast('图片大小不能超过5M')
              return
            }
            // 调用图片压缩方法
            // console.log("成功加载图片，开始压缩图片...")
            this.$utils.compress(e.target.result, (imgDataUrl) => {
              // todo 调用上传图片接口
              this.$request.uploadImg(imgDataUrl).then(data => {
                this.imgList.push(data[0])
              }).catch(e => {
                this.$toast('上传图片失败:' + e.msg)
              })
            })
          }
          // 选取同名文件不会再次触发change事件，所以在加载后替换input控件
          reader.onloadend = (e) => {
            this.clearInputFile()
          }
          reader.readAsDataURL(e.target.files[0])
        } catch (e) {
          console.log('读取图片文件发生了错误')
          console.log(e)
        }
      }
    }
  }
</script>

<style>

</style>